
var Msales = {
    uAddSubmit: '/changeRepository/changeRepositoryAddSubmit',
    editIndex: -1,
    isDg: 0,
    winThat: undefined,
    dgType: undefined,
    storeId :undefined,
    customerId:undefined,
    goodsArr : [],
    allIndex :0

};




Msales.dg = function () {

    $.ajax({
        type: "GET",
        url: "/changeRepository/getAddGoodsList?wearhouseId="+$('#repositoryOut').val(),
        dataType: "json",
        success: function (data) {
            Msales.goodsArr = data;
        }
    });

    Msales.dtable = $('#placeOrderGoods_table');
    Msales.dtable.datagrid({
        // pagination: true,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: true,
        scrollbarSize:0,
        nowrap:false,
        toolbar: [
            {
                text: '增加', iconCls: 'icon-add', handler: function () {

                    Msales.saveDgGoods();
                }
            },
            {
                text: '删除', iconCls: 'icon-remove', handler: function () {
                    Msales.remove();
                }
            }
        ],
        columns: [[
            {field: 'skuId', checkbox: true},//规格id
            {field: 'id', title: '<span style="color:deeppink">品名规格</span>', width: 260, halign: 'center',
                // editor: {type: 'house'},
                editor: {
                type: 'combobox', options: {
                    mode: 'remote',
                    valueField: 'id',
                    textField: 'name',
                    nowrap:false,
                    url: "/changeRepository/getAddGoodsList?wearhouseId="+$('#repositoryOut').val(),
                    method:'get',
                    // onLoadSuccess: function () { //加载完成后,设置选中第一项
                    //     var val = $(this).combobox('getData');
                    //     for (var item in val[0]) {
                    //         if (item == 'id') {
                    //             $(this).combobox('select', val[0][item]);
                    //         }
                    //     }
                    // }
                        onChange: function (value,row) {
                            // $('#goodsAndSkusId').val(value);
                        },
                }
            },  formatter: function (value, row, index) {
                for (var i = 0; i < Msales.goodsArr.length; i++) {
                    if (value == Msales.goodsArr[i].id) {
                        return Msales.goodsArr[i].name;
                    }
                }
                return value;
            }
            },
            {field: 'code', title: '商品编号', width: 60, halign: 'center',align:'center',
            },
            {field: 'repositoryCount', title: '库存数量', width: 60, halign: 'center',align:'center',
            },
            {field: 'count', title: '<span style="color:deeppink">调拨数量</span>', width: 60, halign: 'center',align:'center',
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },


        ]],
        onClickCell: function (index, field) {
            if (Msales.editIndex != index) {
                if (Msales.editIndex > -1) {
                    Msales.dtable.datagrid('endEdit', Msales.editIndex);
                }
                Msales.editIndex = index;
            }


            if (field == "id" || field == "count" ) {
                Msales.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {

            Msales.haha()

        }



    });

    Msales.dtable.datagrid('enableCellEditing');

    //mark2


};

Msales.refresh = function () {
    window.location.reload();
};

Msales.caculate = function () {
    var rows = Msales.dtable.datagrid("getData").rows;
    var goodsFee = 0;
    var totalNUm = 0;
    var totalTransportFeeNum = 0;
    for (var i = 0; i < rows.length; i++) {
        goodsFee = Number(goodsFee) + Number(rows[i].unitPrice) * Number(rows[i].count);
        totalNUm = Number(totalNUm) + Number(rows[i].count);
        totalTransportFeeNum = Number(totalTransportFeeNum) + Number(rows[i].transportFee)
    }
    $("#totalNum").numberbox("setValue", totalNUm);
    // $("#totalFee").numberbox("setValue", goodsFee);
    $("#totalTransportFee").numberbox("setValue", totalTransportFeeNum);

};

Msales.isExist = function (rows, skusId) {
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].skusId == skusId) {
            return true;
        }
    }
    return false;
};
Msales.saveDgGoods = function () {

    document.onkeydown = Msales.keyDown;
    
    var repositoryOutValue = $('#repositoryOut').val();
    if (Msales.isEmpty(repositoryOutValue)){
        $yd.alert("请先选择调出仓库");
        return false;
    }
        


    var rows = Msales.dtable.datagrid("getRows");//mark11111
    var row = rows[rows.length -1];
    Msales.allIndex = rows.length-1;
    if (rows.length >0) {
        Msales.dtable.datagrid('endEdit', rows.length - 1);

        // Msales.haha(rows.length-1, row, true);
}


    Msales.dg();
    var rows = Msales.dtable.datagrid("getData").rows;

            Msales.dtable.datagrid('appendRow', {
                id:":",
                // storeId: Msales.storeId,
                // customId:Msales.customerId,
                skuId: null,
                // goodsName: null,
                count: 1,
                // unitPrice: null,
                // transportFee: null,
                // InvName: null,
                repositoryCount: null,
                code: null,

            }).datagrid('clearSelections');

    // Msales.caculate();

    Msales.isDg = 0;
    Msales.winThat = undefined;
    Msales.dgType = undefined;

    var list = $(":checkbox");
    var tmp = 0;
    for (var i = 1; i < list.length; i++) {
        var td = $(list[i]).closest("td");
        if (td.hasClass("datagrid-row-selected")) {
            tmp = i;
        }
    }
    if (tmp == 0) {
        $(list[1]).closest("td").trigger("click");
    }

    $(":checkbox").attr("tabindex", -1);
};

Array.prototype.contains = function (needle) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

//删除
Msales.remove = function () {
    var sels = Msales.dtable.datagrid('getChecked');
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['id']);
    });

    $.each(ids, function (i, n) {
        var rows = Msales.dtable.datagrid('getRows');
        for (var ii = 0; ii < rows.length; ii++) {
            if (rows[ii].id == n) {
                Msales.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });

    var tds = $(".datagrid-row-selected");
    if (tds.length == 0) {
        var checks = $(":checkbox");
        if (checks.length > 1) {
            $(checks[1]).closest("td").trigger("click");
        }
    }
};


Msales.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};
// Msales.save0 = function () {
//     Msales.save(0);
// };
// Msales.save1 = function () {
//     Msales.save(1);
// };
Msales.save = function () {
    //结束编辑状态
    //mark3
    if (Msales.isEmpty($('#repositoryIn').val())){
        $yd.alert("请选择调入仓库");
        return false;
    }

    if ($('#repositoryIn').val() ==$('#repositoryOut').val()){
        $yd.alert("同一个仓库有什么好调的,答应我换一个仓库，好吗？");
        return false;
    }
        
    var rows = Msales.dtable.datagrid("getRows");//mark11111
    var row = rows[rows.length -1];

    if (rows.length >0) {
        Msales.dtable.datagrid('endEdit', rows.length - 1);


        Msales.haha();
    }




    $('#placeOrderForm').form('submit', {
        url: Msales.uAddSubmit,
        onSubmit: function () {
            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = Msales.dtable.datagrid("getRows");

            if (rows.length == 0) {
                $yd.alert("请添加需要调拨的存货");
                return false;
            }
            


            //封装数据
            $("#rows").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }else {
                $yd.alert(d.message)
            }
        }

    });
};


Msales.keyDown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
};
Msales.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    if (e.keyCode == 13 && Msales.dgType == "goods") {
        Msales.saveDgGoods();
    } else if (e.keyCode == 13 && Msales.dgType == "house") {
        Msales.saveDgHouse();
    }
    if (Msales.isDg != 0 && e.keyCode == 27 && Msales.winThat) {//ESC
        Msales.winThat.close();
    }
    if (Msales.isDg == 0) {
        if (e.keyCode == 45) {//insert
            Msales.plus();
        }
        if (e.keyCode == 46) {//del
            Msales.remove();
        }
        if (e.keyCode == 32) {//space
            var tds = $(".datagrid-row-selected");
            if (tds.length > 0) {
                var check = $(tds).find(":checkbox")[0];
                $(check).trigger("click");
            }
        }
        // if (e.shiftKey && e.keyCode == 83) {
        //     Msales.save(1);//生单入库：Shfit + A
        // }
        // if (e.shiftKey && e.keyCode == 65) {
        //     Msales.save(0);//生单: Shift + S
        // }
        if (e.shiftKey && e.keyCode == 82) {
            Msales.refresh();
        }
    }
};
Msales.init = function () {
    
    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = Msales.mouseClick;

    //快捷键
    document.onkeydown = Msales.keyDown;
    document.onkeyup = Msales.keyUp;

    // setTimeout("$('#orderTime').focus()", 500);
    $("a").attr("tabindex", -1);
    $(":checkbox").attr("tabindex", -1);
};
Msales.mouseClick = function (e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (Msales.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
        if (Msales.editIndex != -1) {
            Msales.dtable.datagrid('endEdit', Msales.editIndex);
            Msales.editIndex = -1;
            Msales.caculate();
        }
    }
};

//全删除
Msales.deleteAll = function () {
    var rows = Msales.dtable.datagrid('getRows');
    for (var i=rows.length;i>0;i--) {
        Msales.dtable.datagrid('deleteRow', i-1);
    }
};
$(function () {
    Msales.obtn = '#mSales_btn';
    Msales.dg(); // 数据表格
    // Msales.btn(); // 初始化按钮
    Msales.init(); // 数据表格

    $("input[id='repositoryOut']").combobox({
        url: "/wWearhouse/list",
        panelHeight: 'auto',
        valueField: 'id',
        method:'post',
        textField: 'name',
        editable: false,
        // onLoadSuccess: function () {
        //     var d = $(this).combobox("getData");
        //     $(this).combobox("setValue", d[0].value);
        // }
        onChange:function () {
            Msales.deleteAll();
        }
    });

    $("input[id='repositoryIn']").combobox({
        url: "/wWearhouse/list",
        panelHeight: 'auto',
        valueField: 'id',
        method:'post',
        textField: 'name',
        editable: false,
        // onLoadSuccess: function () {
        //     var d = $(this).combobox("getData");
        //     $(this).combobox("setValue", d[0].value);
        // }
        onchange:function () {

        }
    });
    $("input[name='changeTime']").datebox({
        required: true,
        editable: false,
        value: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate()
    });


});
Msales.haha = function () {
    var repositoryCountData = 0;
    var invNameData = "";
    a();
    function a() {
        // var value = row['id']
        // var value = $('#goodsAndSkusId').val();
        // console.log(value)
        // console.log(11111111111)
        var rows = Msales.dtable.datagrid("getRows");
        $("#rows").val(JSON.stringify(rows));
        // if (value != null && value != ''){
        //     var goodsId = value.split(',')[0];
        //     var skuId = value.split(',')[1];
            $.ajax({
                url:'/changeRepository/changeRepositoryAddDetail',
                // '?tticarGoodsId='
                // +goodsId+'&skuValue='+skuId+'&customId='+$("#custom").combobox('getValue')+'&rows='+$('#rows').val()
                // +'&addrId='+$("#customAddr").combobox('getValue')+'&sellStoreId='+$("#ttstoreId").combobox('getValue'),
                type:'post',
                data :{
                    wearhouseId:$('#repositoryOut').val(),
                    rows:$('#rows').val(),
                },
                async:false,
                success:function (data) {

                    for (var i =0;i< data.length; i++){
                        var repositoryCountData = 0;
                        var code = "";
                        var count = data[i].count;
                        if (count > data[i].repositoryCount) {
                            count = data[i].repositoryCount;
                        }
                        repositoryCountData=data[i].repositoryCount;
                        code=data[i].code;

                        Msales.dtable.datagrid('updateRow', {

                            index: i ,
                            row: {
                                code : code,
                                repositoryCount: repositoryCountData,
                                count :count,

                            }
                        });

                    }

                }
            });
        // }


    };


    Msales.caculate();

}


//重置按钮
var resetBtn = document.getElementById("resetButton");
resetBtn.addEventListener("click", function() {
    $("#repositoryOut").combobox("setValue", "");
    $("#repositoryIn").combobox("setValue", "");
});
//保存按钮
var resetBtn = document.getElementById("saveButton");
resetBtn.addEventListener("click", function() {
    Msales.save();
});
